package com.mowh.multithreading.balking.saver;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @author mowh1gd
 * @create 2023/11/14 16:35
 */
public class Data { //扮演GuardedObject角色
    private final String fileName;
    private String content;
    private boolean changed; // 扮演GuardedObject角色的state，而changed=true是守护条件。

    public Data(String fileName, String content) {
        this.fileName = fileName;
        this.content = content;
        this.changed = true;
    }
    public synchronized void change(String newContent) {//扮演GuardedObject角色的stateChangingMethod
        content = newContent;
        changed = true;
    }
    public synchronized void save() throws IOException {//扮演GuardedObject角色的guardedMethod
        if (!changed) { //不满足守护条件，则balk。
            return;// 这里balk并不返回任何消息通知调用端，即忽略balk；也可以通过异常或返回值来表示发生了balk。
        }
        doSave();//满足守护条件，则进行保存。声名为synchronized，把处理放到临界区。
        changed = false;
    }
    private void doSave() throws IOException {
        System.out.println(Thread.currentThread().getName() + " calls doSave, content= " + content);
        FileWriter writer = new FileWriter(fileName);
        writer.write(content);
        writer.close();
    }
}
